var ajaxQueue = $({});
var ajaxcount = 0;
var processed = 0;
var success = 0;
var failed = 0;
var i = 0;

$.ajaxQueue = function(ajaxOpts) {
	// Hold the original complete function.
	var oldComplete = ajaxOpts.complete;

	// Queue our ajax request.
	ajaxQueue.queue(function(next) {
		// Create a complete callback to fire the next event in the queue.
		ajaxOpts.complete = function() {
			// Fire the original complete if it was there.
			if (oldComplete) {
				oldComplete.apply(this, arguments);
			}
			// Run the next query in the queue.
			next();
		};

		// Run the query.
		$.ajax(ajaxOpts);
	});
};

function grabperpage() {
	$('.legresult ').show();
	$.ajax({
		type : 'POST',
		url : $($('#cari')).attr('action'),
		data : $($('#cari')).serialize(),
		beforeSend : function() {
				$('.resultall').html('<center><img src="../assets/img/loading.gif" /></center>');
				$('.grab').find(":checkbox").prop("checked", false);
				$(".dograb").prop("disabled",false);
				$('.grab').hide();
			},
			success : function(data) {
				$('.pagination').show();
				//$('#debug').html(data);
				$('.resultall').html('');


				var lang = '';
				var obj = $.parseJSON(data);
				var i = 1;
				$.each(obj, function() {
					var numkey= ($('.page').val()*8)-8+i;
					key = $('[name="key"]').val();
					if ((i == 1) || ((i - 1) % 3) == 0) {
						$('.resultall').append('<div class="row-fluid">');
					}
					$('.resultall').append('<div class="thumbnail span3"><a href="' + this['url'] + '" target="_blank"><center><img alt="300x200" src="' + this['tbUrl'] + '"></a></br><div class="size">' + this['height'] + 'x' + this['width'] + '</div><input type="text" class="span11" value="' + key + ' ' + numkey + '"/><input type="checkbox" /></div>');
					if ((i% 3) == 0) {
						$('.resultall').append('</div>');	
					}
					i++;
				});
				$('.grab').show();
			},
			error : function(xhr, textStatus, errorThrown) {
				$('resultall').html('error');

			}
	})
	return false;
}


$(document).ready(function() {
	$('#cari').submit(function() {
		$('.legresult ').show();
		$('.page').val('1');
		$('.on').html($('.page').val());
		$.ajax({
			type : 'POST',
			url : $(this).attr('action'),
			data : $(this).serialize(),
			beforeSend : function() {
				$('.resultall').html('<center><img src="../assets/img/loading.gif" /></center>');
				$('.grab').find(":checkbox").prop("checked", false);
				$(".dograb").prop("disabled",false);
				$('.grab').hide();
			},
			success : function(data) {
				$('.pagination').show();
				//$('#debug').html(data);
				$('.resultall').html('');

				var lang = '';
				var obj = $.parseJSON(data);
				var i = 1;
				$.each(obj, function() {
					key = $('[name="key"]').val();
					if ((i == 1) || ((i - 1) % 3) == 0) {
						$('.resultall').append('<div class="row-fluid">');
					}
					$('.resultall').append('<div class="thumbnail span3"><a href="' + this['url'] + '" target="_blank"><center><img alt="300x200" src="' + this['tbUrl'] + '"></a></br><div class="size">' + this['height'] + 'x' + this['width'] + '</div><input type="text" class="span11" value="' + key + ' ' + i + '"/><input type="checkbox" /></div>');
					if ((i% 3) == 0) {
						$('.resultall').append('</div>');	
					}
					i++;
				});
				$('.grab').show();
			},
			error : function(xhr, textStatus, errorThrown) {
				$('.resultall').html('error');
			}
		})
		return false;
	});

	$('.dograb').click(function() {
		$('.progress').show();
		$('.leglog').show();
		$(".dograb").prop("disabled",true);
		var count = $("input:checked").length;
		//alert(count);
		
		$(".thumbnail").each(function(index) {
			if ($(this).find(":checkbox").is(':checked')) {
				var url = $(this).find("a").prop('href');
				var size = $(this).find(".size").html();
				var sizes = size.split("x");
				var height = sizes[0];
				var width = sizes[1];
				var name = $(this).find(":text").attr('value');
				var myPost = 'name=' + name + '&height=' + height + '&width=' + width + '&url=' + url;
				ajaxcount++;
				$(".ajaxcount").html(processed + "/" + ajaxcount);
				$.ajaxQueue({

					type : "Post",
					url : "saveimage",
					datatype : "json",
					data : myPost,
					timeout : 10000000,
					beforeSend : function() {
						i++;
						var persen = (i / (ajaxcount)) * 100;
						$('.progress').html('<div class="bar" style="width: ' + persen + '%;"></div>');
						$('.status').html('<span class="label label-success">grabbing</span></br>');
					},
					success : function(response) {
						$('.logres').append(response);
					},
					error : function(xhr, textStatus, errorThrown) {
						$('.logres').append('<span class="label label-important">Timeout ' + name + '</span></br>');
					},
					complete : function() {
						processed++;
						$(".ajaxcount").html(processed + '/' + ajaxcount);
						if(processed==ajaxcount)
						{
							$('.status').html('<span class="label label-success">complete</span></br>');
						}
					}
				});
			}
		});
	});

	$('.grab :checkbox').change(function() {
		if ($(this).is(':checked')) {
			$(".thumbnail :checkbox").prop("checked", true);
			//alert('checked');
		} else {
			//alert('unchecked');
			$(".thumbnail :checkbox").prop("checked", false);
		}
	});
	$('.next').click(function() {
		var page = $('.page').val();
		$('.page').val(parseInt(page) + 1 + '');
		$('.on').html($('.page').val());
		grabperpage();
	});
	$('.prev').click(function() {
		if ($('.page').val() > 1) {
			var page = $('.page').val();
			$('.page').val(parseInt(page) - 1 + '');
			$('.on').html($('.page').val());
			grabperpage();
		}

	});
})